package com.bit.catmoney;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Handler;
import android.os.Message;

public class GameServer {

	String rootPath = "http://godling2.cafe24.com/gm/index.php/rank/";
	String rankAddr = rootPath + "top/format/json";
	Handler mAfterDown = null;

	public void receiveRankTop(Handler afterDown) {
		mAfterDown = afterDown;
		DownThread thread = new DownThread(rankAddr);
		thread.start();
	}
	
	public void sendScore(String nickname, String score, Handler afterDown) {
		mAfterDown = afterDown;
		String scoreAddr = rootPath + "add/n/"+nickname+"/s/"+ score;
		DownThread thread = new DownThread(scoreAddr);
		thread.start();
	}

	class DownThread extends Thread {
		private String mAddr;

		public DownThread(String addr) {
			mAddr = addr;
		}

		public void run() {
//			Log.d("testrun", mAddr);
			HttpGet get = new HttpGet(mAddr);
			DefaultHttpClient client = new DefaultHttpClient();
			try {
				client.execute(get, mResHandler);
			} catch (Exception e) { ; }
		}
	}

	ResponseHandler<String> mResHandler = new ResponseHandler<String>() {
		public String handleResponse(HttpResponse response)
				throws ClientProtocolException, IOException {
//			Log.d("testResponseHandler", "start");
			StringBuilder html = new StringBuilder();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						response.getEntity().getContent()));
				for (;;) {
					String line = br.readLine();
					if (line == null)
						break;
					html.append(line + '\n');
				}
				br.close();

				if (mAfterDown != null) {
//					Log.d("testResponseHandler", html.toString());
					Message message = mAfterDown.obtainMessage();
					message.obj = html.toString();
					mAfterDown.sendMessage(message);
				}
			} catch (Exception e) { ; }
			
			return html.toString();
		}
	};
}
